<template>
  <a-select
    v-if="async"
    showSearch
    labelInValue
    @search="loadData"
    :placeholder="placeholder"
    v-model="selectedAsyncValue"
    style="width: 100%"
    :filterOption="filterOption"
    @change="handleAsyncChange"
    allowClear
    :disabled="disabled"
    :notFoundContent="loading ? undefined : null"
  >
    <a-spin v-if="loading" slot="notFoundContent" size="small" />
    <slot></slot>
    <div slot="dropdownRender" slot-scope="menu">
      <v-nodes :vnodes="menu" />
      <div v-if="isdropdownRender">
        <a-divider style="margin: 4px 0" />
        <div style="padding: 4px 8px; cursor: pointer" @click="addItem"><a-icon type="plus" /> 新建</div>
      </div>
    </div>
    <a-select-option v-for="d in options" :key="d.value" :value="d.value"
      ><span v-show="showCode">{{ ' [' + d.value + '] &nbsp;' }}</span
      ><span>{{ d.text }}</span></a-select-option
    >
  </a-select>

  <a-select
    v-else
    showSearch
    :disabled="disabled"
    :placeholder="placeholder"
    optionFilterProp="children"
    style="width: 100%"
    @change="handleChange"
    :filterOption="filterOption"
    v-model="selectedValue"
    allowClear
    :notFoundContent="loading ? undefined : null"
  >
    <a-spin v-if="loading" slot="notFoundContent" size="small" />
    <slot></slot>
    <div slot="dropdownRender" slot-scope="menu">
      <v-nodes :vnodes="menu" />
      <div v-if="isdropdownRender">
        <a-divider style="margin: 4px 0" />
        <div style="padding: 4px 8px; cursor: pointer" @click="addItem"><a-icon type="plus" /> 新建</div>
      </div>
    </div>
    <a-select-option v-for="d in options" :key="d.value" :value="d.value"
      ><span v-show="showCode">{{ ' [' + d.value + '] &nbsp;' }}</span
      ><span>{{ d.text }}</span></a-select-option
    >
  </a-select>
</template>

<script>
import { ajaxGetDictItems } from '@/api/api'
import debounce from 'lodash/debounce'
import { getAction } from '../../api/manage'

export default {
  name: 'JSearchSelectTag',
  components: {
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  props: {
    disabled: Boolean,
    value: String,
    otherField: String,
    dict: String,
    dictUrl: String,
    dictUrlCustomer: String,
    dictOptions: Array,
    async: Boolean,
    showCode: {
      type: Boolean,
      default: false,
    },
    placeholder: {
      type: String,
      default: '请选择',
      required: false,
    },
    isdropdownRender: {
      type: Boolean,
      default: () => false,
    },
  },
  data() {
    this.loadData = debounce(this.loadData, 800) //消抖
    this.lastLoad = 0
    return {
      loading: false,
      selectedValue: [],
      selectedAsyncValue: [],
      options: [],
    }
  },
  created() {
    this.initDictData()
    if (this.dictUrlCustomer) {
      this.initDictUrlCustomerData()
    }
  },
  watch: {
    value: {
      immediate: true,
      handler(val) {
        if (!val) {
          this.selectedValue = []
          this.selectedAsyncValue = []
        } else {
          this.initSelectValue()
        }
      },
    },
    dictOptions: {
      immediate: true,
      deep: true,
      handler(val) {
        if (val) this.options = val
      },
    },
    dict: {
      handler() {
        this.initDictData()
      },
    },
    dictUrl: {
      handler() {
        this.initDictUrlData()
      },
    },
    dictUrlCustomer: {
      handler() {
        this.initDictUrlCustomerData()
      },
    },
  },
  methods: {
    initSelectValue() {
      if (this.async) {
        if (!this.selectedAsyncValue || !this.selectedAsyncValue.key || this.selectedAsyncValue.key != this.value) {
          //console.log("这才请求后台")
          let url = `/online/dict/getDictItems/${this.dict}`
          if (this.dictUrl) {
            url = `/online/api/select/${this.dictUrl}`
          }
          if(this.dict||this.dictUrl){
            getAction(url, { keywordId: this.value, keyword: this.value, otherField: this.otherField }).then((res) => {
              if (res.success) {
                let obj = {
                  value: this.value,
                  label: res.result[0].title,
                }
                this.selectedAsyncValue = { ...obj }
              }
            })
          }
        }
      } else {
        this.selectedValue = this.value
      }
    },
    loadData(value) {
      console.log('数据加载', value)
      this.lastLoad += 1
      const currentLoad = this.lastLoad
      this.options = []
      this.loading = true
      // 字典code格式：table,text,code
      let url = `/online/dict/getDictItems/${this.dict}`
      if (this.dictUrl) {
        url = `/online/api/select/${this.dictUrl}`
      }
      getAction(url, { keyword: value, otherField: this.otherField }).then((res) => {
        this.loading = false
        if (res.success) {
          if (currentLoad != this.lastLoad) {
            return
          }
          this.options = res.result
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    initDictData() {
      if (!this.async) {
        //如果字典项集合有数据
        if (this.dictOptions && this.dictOptions.length > 0) {
          this.options = [...this.dictOptions]
        } else {
          //根据字典Code, 初始化字典数组
          ajaxGetDictItems(this.dict, { otherField: this.otherField }).then((res) => {
            if (res.success) {
              this.options = res.result
            }
          })
        }
      }
    },
    initDictUrlData() {
      if (!this.async) {
        //如果字典项集合有数据
        getAction('/online/api/select/' + this.dictUrl, { otherField: this.otherField }).then((res) => {
          if (res.success) {
            this.options = res.result
          }
        })
      }
    },
    initDictUrlCustomerData() {
      if (!this.async) {
        //如果字典项集合有数据
        getAction('/online/api/' + this.dictUrlCustomer, { infoStatusId: '3' }).then((res) => {
          if (res.success) {
            let arr1 = []
            let arr2 = []
            res.result.forEach((item) => {
              if (item.removed == 'N') {
                arr1.push({
                  label: item.relatedCustomer_dictText,
                  text: item.relatedCustomer_dictText,
                  value: item.relatedCustomer,
                  key: item.relatedCustomer,
                })
              }
            })
            let obj = {}
            arr2 = arr1.reduce((item, next) => {
              obj[next.value] ? '' : (obj[next.value] = true && item.push(next))
              return item
            }, [])
            this.options = arr2
          }
        })
      }
    },
    filterOption(input, option) {
      return option.componentOptions.children[1].children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
    },
    handleChange(selectedValue) {
      //console.log("selectedValue",selectedValue)
      this.selectedValue = selectedValue
      this.callback()
    },
    handleAsyncChange(selectedObj) {
      this.selectedAsyncValue = selectedObj
      this.selectedValue = selectedObj.key
      this.callback()
    },
    callback() {
      let row = {}
      this.options.forEach((item) => {
        if (item.key == this.selectedValue) {
          row = item
        }
      })
      this.$emit('change', this.selectedValue, row)
    },
    setCurrentDictOptions(dictOptions) {
      this.options = dictOptions
    },
    getCurrentDictOptions() {
      return this.options
    },
    addItem() {
      this.$emit('addDropItem', {})
    },
  },
  model: {
    prop: 'value',
    event: 'change',
  },
}
</script>

<style scoped>
</style>